package org.example.config;


import org.reactivestreams.Publisher;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

// 响应包装类（用于缓存响应体）
class CachedResponseWrapper extends org.springframework.http.server.reactive.ServerHttpResponseDecorator {
    private final StringBuilder body = new StringBuilder();

    public CachedResponseWrapper(ServerHttpResponse delegate) {
        super(delegate);
    }

    @Override
    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
        return super.writeWith(Flux.from(body).doOnNext(buffer -> {
            byte[] bytes = new byte[buffer.readableByteCount()];
            buffer.read(bytes);
            this.body.append(new String(bytes, StandardCharsets.UTF_8));
        }));
    }

    public String getBody() {
        return body.toString();
    }
}
